<!-- vue/src/components/router.vue -->
<template>
  <div class="main">
    <el-menu
        :default-active="'/shop'"
        class="el-menu-vertical-demo"
        router
        style="min-width: 200px; border-right: 0;"
    >
      <!-- 首页菜单 -->
      <el-menu-item index="/shop">
        <template #title>
          <i class="el-icon-house" style="margin-right: 8px;"></i>
          <span>首页</span>
        </template>
      </el-menu-item>

      <!-- 购物车列表（父菜单，包含商品子菜单） -->
      <el-sub-menu index="list">
        <template #title>
          <i class="el-icon-shopping-cart-2" style="margin-right: 8px;"></i>
          <span>购物车列表</span>
        </template>

        <!-- 动态生成商品子菜单 -->
        <template v-for="product in productList" :key="product.id">
          <el-menu-item :index="`/list/details/?id=${product.id}`">
            <template #title>
              <i class="el-icon-gift" style="margin-right: 8px; font-size: 12px;"></i>
              <span>{{ product.name }}</span>
            </template>
          </el-menu-item>
        </template>
      </el-sub-menu>

      <!-- 用户信息菜单 -->
      <el-menu-item index="/user">
        <template #title>
          <i class="el-icon-user" style="margin-right: 8px;"></i>
          <span>用户信息</span>
        </template>
      </el-menu-item>
    </el-menu>

    <div class="compt">
      <RouterView></RouterView>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref,onMounted } from "vue";
import axios from "axios";
// 调用后端API获取商品列表
const productList = ref([]);

onMounted(()=>{
  fetchProducts()
})
// 用axios发送异步http请求用于从后端 API 获取商品列表数据
const fetchProducts = async () => {
  try {
    const res = await axios.get('/api/products');
    productList.value = res.data;
  } catch (err) {
    console.error('获取商品列表失败:', err);
  }
};
</script>

<style scoped>
.main {
  width: 800px;
  margin: auto;
  display: flex;
}

.el-menu-vertical-demo {
  min-width: 200px;
}

.compt {
  flex: 1;
  border: 1px solid black;
  padding: 20px;
}
</style>